<?php

namespace app\api\controller;

use Exception;
use think\Controller;
use think\Request;

/**
 *  
 */
class Jinju extends Controller
{

    const PARTNER_NO = '65f6e7f8c36994e8060294cc8c2ac281';
    const KEY = 'f92200faea6e68961443564cddaa3fac';

    public function test(){
        $data = [
            'Axis'=>[
                '200K'=>'82896',
            ],
            'By.U'=>[
                '200K'=>'82889',
            ],
            'Ceria'=>[

            ],
            'Indosat'=>[
                '200K'=>'82878',
                '20K'=>'82881',
            ],
            'Net1'=>[
                '200K'=>'82878',
                '20K'=>'82881',
            ],
            'Smartfren'=>[
                '200K'=>'82850',
                '20K'=>'82853',
            ],
            'Telkomsel'=>[
                '200K'=>'82870',
                '20K'=>'82872',
            ],
            'Three'=>[
                '200K'=>'82862',
                '20K'=>'82865',
            ],
            'XL Axiata'=>[
                '200K'=>'82838',
            ],
        ];
        var_dump(json_encode($data));die;
        return $data;
    }

    public function mobile_order(){
        try{
            $param = Request::instance()->param();
            mylog($param);
            //发送到钉钉
            $server_config_info = db('accounts_info', 'db_config2')->where(['UserID'=>$param['user_id']])->find();
            $this->dingding($param['amount'],$server_config_info,$param['country_code']);
            
            if(empty($param['mobile']) || empty($param['amount']) || empty($param['user_id']) || empty($param['country_code'])){
                throw new Exception('缺少参数');
            }
            $data = [
                'partner_no'=>self::PARTNER_NO,
                'datetime'=>date('YmdHis'),
                'country_code'=>$param['country_code']
            ];
    
            $data['sign']=md5($this->signData($data).self::KEY);
            $res = $this->post_https('https://kboss-api.kqlink.com/API/2.1/mobile-number/'.$param['mobile'],$data);
            mylog($res);
            $obj = json_decode($res,true);
            if($obj['data']['returnCode'] != 'SUCCESS' || empty($obj['data']['result']['name'])){
                throw new Exception('请求异常');
            }
            
            $server_config_info = db('server_config_info', 'db_config2')->where(['ServerName'=>'jinju_order'])->find();
            $config = json_decode($server_config_info['Content'],true);
            if(empty($config[$param['country_code']][$obj['data']['result']['name']][$param['amount']])){
                throw new Exception('未找到改服务商或者服务商下面的金额配置');
            }
            $product_id = $config[$param['country_code']][$obj['data']['result']['name']][$param['amount']];
            db('order_mobile', 'db_operatelog')->insert([
                'add_time'=>date('Y-m-d H:i:s'),
                'user_id'=>$param['user_id'],
                'amount'=>$param['amount'],
                'request_no'=>'ju'.time().rand(1000,9999),
                'product_id'=>$product_id,
                'country_name'=>$param['country_code'],
                'service_name'=>$obj['data']['result']['name'],
                'mobile'=>$param['mobile'],
                'status'=>0
            ]);
            exit(json_encode(['code'=>1,'msg'=>'成功-等客服手动发货']));
        }catch(\Exception $e){
            mylog('jijuhuafei:'.$e->getMessage().' line:'.$e->getLine().' file:'.$e->getFile());
            db('order_mobile', 'db_operatelog')->insert([
                'add_time'=>date('Y-m-d H:i:s'),
                'user_id'=>empty($param['user_id'])?'':$param['user_id'],
                'amount'=>empty($param['amount'])?'':$param['amount'],
                'request_no'=>'ju'.time().rand(1000,9999),
                'product_id'=>'',
                'country_name'=>empty($param['country_code'])?'':$param['country_code'],
                'service_name'=>'',
                'mobile'=>empty($param['mobile'])?'':$param['mobile'],
                'status'=>1,
                'msg'=>$e->getMessage()
            ]);
            exit(json_encode(['code'=>0,'msg'=>$e->getMessage()]));
        }
    }
    
    public function order(){
        $data = [
            'partner_no'=>self::PARTNER_NO,
            'datetime'=>date('YmdHis'),
            'request_no'=>'ju167936101298071',
            'product_id'=>'82868',
            'account'=>'081222069799',
            'callback_url'=>'http://pay.arichfishing.com/api/Jinju/notify',
        ];
        $data['sign']=md5($this->signData($data).self::KEY);
        $res = $this->post_https('https://kboss-api.kqlink.com/API/2.1/order',$data);
        var_dump($res);die;
    }

    public function query(){
        $data = [
            'partner_no'=>self::PARTNER_NO,
            'datetime'=>date('YmdHis'),
            'serial_no'=>'67ffc2b3a5b448ffa3c05cbd81d49c81',
            'request_no'=>'1234567',
        ];
        $data['sign']=md5($this->signData($data).self::KEY);
        $res = $this->post_https('https://kboss-api.kqlink.com/API/2.1/query',$data);
        var_dump($res);die;
    }

    public function notify(){
        $param = Request::instance()->param();
        mylog($param);
        try{
            $sign=md5($this->signData($param).self::KEY);
            if($sign != $param['sign']){
                throw new \Exception('签名错误');
            }

            $order_mobile = db('order_mobile', 'db_operatelog')->where(['request_no'=>$param['request_no']])->find();
            if(empty($order_mobile)){
                throw new \Exception('request_no 不存在');
            }
            if($order_mobile['status'] == 1){
                return 'SUCCESS';
            }

            if($param['status'] != 'success'){
                throw new \Exception($param['result']);
            }
            
            db('order_mobile', 'db_operatelog')->where(['request_no'=>$param['request_no']])->update(['status'=>4,'msg'=>$param['result']]);
            return 'SUCCESS';
        }catch(\Exception $exception){
            mylog('jinju-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            db('order_mobile', 'db_operatelog')->where(['request_no'=>$param['request_no']])->update(['status'=>5,'msg'=>$exception->getMessage()]);
            return 'SUCCESS';
        }
    }


    public function countries()
    {
        $data = [
            'partner_no'=>self::PARTNER_NO,
            'datetime'=>date('YmdHis'),
        ];
        $data['sign']=md5($this->signData($data).self::KEY);
        //查询开通的国家
        // $res = $this->post_https('https://kboss-api.kqlink.com/API/2.1/countries',$data);
        // var_dump($res);die;
        $res = '{
            "data": {
                "returnCode": "SUCCESS",
                "errorCode": "JU0000",
                "returnMsg": "请求成功",
                "result": [
                    {
                        "name": "印度尼西亚",
                        "country_code": "ID",
                        "iso_code": "IDN",
                        "area_number": "62"
                    },
                    {
                        "name": "柬埔寨",
                        "country_code": "KH",
                        "iso_code": "KHM",
                        "area_number": "855"
                    },
                    {
                        "name": "菲律宾",
                        "country_code": "PH",
                        "iso_code": "PHL",
                        "area_number": "63"
                    },
                    {
                        "name": "缅甸",
                        "country_code": "MM",
                        "iso_code": "MMR",
                        "area_number": "95"
                    },
                    {
                        "name": "马来西亚",
                        "country_code": "MY",
                        "iso_code": "MYS",
                        "area_number": "60"
                    },
                    {
                        "name": "巴基斯坦",
                        "country_code": "PK",
                        "iso_code": "PAK",
                        "area_number": "92"
                    },
                    {
                        "name": "新加坡",
                        "country_code": "SG",
                        "iso_code": "SGP",
                        "area_number": "65"
                    },
                    {
                        "name": "泰国",
                        "country_code": "TH",
                        "iso_code": "THA",
                        "area_number": "66"
                    },
                    {
                        "name": "美国",
                        "country_code": "US",
                        "iso_code": "USA",
                        "area_number": "1"
                    },
                    {
                        "name": "越南",
                        "country_code": "VN",
                        "iso_code": "VNM",
                        "area_number": "84"
                    }
                ]
            },
            "page": []
        }';
        $countries = json_decode($res,true);
        $array = [];
        foreach($countries['data']['result'] as $v){
            $services = $this->post_https('https://kboss-api.kqlink.com/API/2.1/services/'.$v['country_code'],$data);
            $services = json_decode($services,true);
            $array[$v['country_code']] = $services;
        }

        $services = json_encode($array);

        // $services = '{"ID":{"data":{"returnCode":"SUCCESS","errorCode":"JU0000","returnMsg":"请求成功","result":[{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"Axis","full_name":"Axis Indonesia","id":499},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"By.U","full_name":"By.U Indonesia","id":761},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"Ceria","full_name":"Ceria Indonesia","id":595},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"Indosat","full_name":"Indosat Indonesia","id":203},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"Net1","full_name":"Net1 Indonesia","id":496},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"Smartfren","full_name":"SmartFren Indonesia","id":204},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"Telkomsel","full_name":"Telkomsel Indonesia","id":205},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"Three","full_name":"Three Telecom Indonesia","id":206},{"country":{"name":"印度尼西亚","country_code":"ID","iso_code":"IDN","area_number":"62"},"name":"XL Axiata","full_name":"XL Indonesia","id":207}]},"page":[]},"MY":{"data":{"returnCode":"SUCCESS","errorCode":"JU0000","returnMsg":"请求成功","result":[{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"CELCOM","full_name":"Celcom Malaysia","id":299},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"DIGI","full_name":"DiGi Malaysia","id":300},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"Halo Telco","full_name":"Halo Telco Malaysia","id":897},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"MAXIS","full_name":"Maxis Malaysia","id":301},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"RedOne","full_name":"RedOne Malaysia","id":896},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"TUNETALK","full_name":"TuneTalk Malaysia","id":302},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"UMOBILE","full_name":"UMobile Malaysia","id":303},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"Unifi","full_name":"Unifi Malaysia","id":304},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"Xox","full_name":"Xox Malaysia","id":822},{"country":{"name":"马来西亚","country_code":"MY","iso_code":"MYS","area_number":"60"},"name":"Yes","full_name":"Yes Malaysia","id":898}]},"page":[]},"VN":{"data":{"returnCode":"SUCCESS","errorCode":"JU0000","returnMsg":"请求成功","result":[{"country":{"name":"越南","country_code":"VN","iso_code":"VNM","area_number":"84"},"name":"Beeline","full_name":"Beeline Vietnam","id":466},{"country":{"name":"越南","country_code":"VN","iso_code":"VNM","area_number":"84"},"name":"Gmobile","full_name":"Gmobile Vietnam","id":467},{"country":{"name":"越南","country_code":"VN","iso_code":"VNM","area_number":"84"},"name":"MOBIFONE","full_name":"Mobifone Vietnam","id":468},{"country":{"name":"越南","country_code":"VN","iso_code":"VNM","area_number":"84"},"name":"VietnamMobile","full_name":"VietnamMobile Vietnam","id":470},{"country":{"name":"越南","country_code":"VN","iso_code":"VNM","area_number":"84"},"name":"VIETTEL","full_name":"Viettel Mobile Vietnam","id":471},{"country":{"name":"越南","country_code":"VN","iso_code":"VNM","area_number":"84"},"name":"VINAPHONE","full_name":"Vinaphone Vietnam","id":472}]},"page":[]}}';
        $services = json_decode($services,true);
        $aaa = [];
        foreach($services as $v){
            foreach ($v['data']['result'] as $vv) {
                $data = [
                    'partner_no'=>self::PARTNER_NO,
                    'datetime'=>date('YmdHis'),
                    'country_code'=>$vv['country']['country_code'],
                    'carrier'=>$vv['id'],
                    'type'=>'HF',
                    'pageSize'=>1000
                ];
                $data['sign']=md5($this->signData($data).self::KEY);
                $obj = $this->post_https('https://kboss-api.kqlink.com/API/2.1/product',$data);
                $obj = json_decode($obj,true);
                if(empty($obj['data']['result'])){
                    continue;
                }
                foreach($obj['data']['result'] as $vvv){
                    $aaa[$vv['country']['country_code']][$vv['name']][$vvv['name']] = $vvv['id'];
                }
            }
        }
        var_dump(json_encode($aaa));die;

        var_dump(11);die;

        
    }

    //
    public function services(){
        $data = [
            'partner_no'=>self::PARTNER_NO,
            'datetime'=>date('YmdHis'),
        ];

        $data['sign']=md5($this->signData($data).self::KEY);

        $res = $this->post_https('https://kboss-api.kqlink.com/API/2.1/services/MY',$data);
        var_dump($res);die;
    }

    public function product(){
        $data = [
            'partner_no'=>self::PARTNER_NO,
            'datetime'=>date('YmdHis'),
            'country_code'=>'ID',
            'carrier'=>496,
            'type'=>'HF',
        ];

        $data['sign']=md5($this->signData($data).self::KEY);

        $res = $this->post_https('https://kboss-api.kqlink.com/API/2.1/product',$data);
        
        var_dump($res);die;
    }

    



    public function signData($data)
    {
        ksort($data);
        $tmp = [];
        foreach ($data as $k => $v) {
            if($k == 'sign'){
                continue;
            }
            $tmp[] = $k . '=' . $v;
        }
        $str = implode('&', $tmp);
        return $str;
    }
    function post_https($url,$data)
    { // 模拟提交数据函数
        $curlPost = json_encode($data);

        $headers = array(
            "Content-Type: application/json;",
        );

        $postUrl = $url;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 1);//设置header
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);//提交的参数
        $return = curl_exec($curl);//运行curl

        list($headers, $response) = explode("\r\n\r\n", $return, 2);
        $headers = explode("\r\n", $headers);
        curl_close($curl);
        $page = [];
        foreach($headers as $header) {
            if (stripos($header, 'X-Total:') !== false) {
                $page['Total'] = substr($header,9);
            }
            if (stripos($header, 'X-Total-Pages:') !== false) {
                $page['Total_Pages'] = substr($header,15);
            }
            if (stripos($header, 'X-Per-Page:') !== false) {
                $page['Per_Page'] = substr($header,11);
            }
            if (stripos($header, 'X-Page:') !== false) {
                $page['Page'] = substr($header,8);
            }
            if (stripos($header, 'X-Next-Page:') !== false) {
                $page['Next_Page'] = substr($header,13);
            }
        }
        $data = [
            'data'=>json_decode($response,true),
            'page'=>$page
        ];
        mylog($data);
        return json_encode($data);

    }


    
    public function dingding($amount,$accounts_info,$country_code)
    {
        try{
                $message="【金蟾捕鱼--后台反馈--话费兑换】
                ■■■■■■■■■■■■■■
                用户ID:【".$accounts_info['UserID']."】
                用户昵称:【".$accounts_info['NickName']."】
                VIP等级:【".$accounts_info['VipLevel']."】
                渠道名称：【".$accounts_info['SpreaderID']."】
                版本号：【".$accounts_info['ClientVersion']."】
                №№№№№№№№№№№№№№№
                兑换话费:【".$amount."】
                国家编码:【".$country_code."】
                №№№№№№№№№№№№№№№
                请尽快处理";
                $webhook = "https://oapi.dingtalk.com/robot/send?access_token=8d7017ba2f8e4cf2e05ca330747ac09a26bdce325dad8b387323db116838f098";
                echo $message.PHP_EOL;
                $data = array ('msgtype' => 'text','text' => array ('content' => $message));
                $data_string = json_encode($data);

                $result = $this->request_by_curl($webhook, $data_string); 
                echo $result;
        }catch(Exception $exception){

        }
    }
    
    function request_by_curl($remote_server, $post_string) {  
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1); 
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); 
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);      
        return $data;  
    }  

    
}

